package com.cloudwave.trailends.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cloudwave.base.action.AppAction;
import com.cloudwave.base.entity.QueryEntity;
import com.cloudwave.base.entity.ResultEntity;
import com.cloudwave.fwcore.utils.DateUtils;
import com.cloudwave.trailends.domain.LinePoint;
import com.cloudwave.trailends.domain.RidingLine;
import com.cloudwave.trailends.domain.UserSignLog;
import com.cloudwave.trailends.entity.SyncDataEntity;
import com.cloudwave.trailends.entity.SyncIdEntity;
import com.cloudwave.trailends.service.LinePointService;
import com.cloudwave.trailends.service.RidingLineService;
import com.cloudwave.trailends.service.UserService;

/**
 * @description 数据同步业务
 * @author DolphinBoy
 * @date 2014年1月13日
 * API版本控制
 * http://blog.csdn.net/hengyunabc/article/details/20506345
 * 基础代号:700
 */

@Controller
@RequestMapping("/api/sync")
public class SyncAction extends AppAction {
	private static Logger logger = LoggerFactory.getLogger(SyncAction.class);
	
	@Resource
	private RidingLineService ridingLineService;
	@Resource
	private LinePointService linePointService;
	@Resource
	private UserService userService;
	
	
	@RequestMapping(method=RequestMethod.POST, value="/upload1")
	public @ResponseBody ResultEntity upload1(@RequestParam("data") String data
//			, @RequestParam("points") String points
			) {
		RidingLine ridingLine = null;
		List<LinePoint> lpList = null;
		try {
			if (StringUtils.isNotEmpty(data)) {
				ridingLine = JSON.parseObject(data, RidingLine.class);
				lpList = ridingLine.getLpList();
			}
		} catch (Exception e) {
			logger.error("parse json string error.", e);
			return resultEntity.failure();
		}
		
		if (ridingLine == null && CollectionUtils.isEmpty(lpList)) {
			return resultEntity.failure();
		}
		
		try {
			if (ridingLine != null && CollectionUtils.isNotEmpty(lpList)) {
				super.setWho(ridingLine, DateUtils.now());
				super.setWho(lpList, DateUtils.now());
				ridingLineService.saveLineAndPoints(ridingLine, lpList);
			}
		} catch (Exception e) {
			logger.error("upload data error.", e);
			return resultEntity.failure();
		}
		return resultEntity.success();
	}
	
	
	@RequestMapping(method=RequestMethod.POST, value="/delete")
	public @ResponseBody ResultEntity delete(HttpServletRequest request
			, @RequestParam("data") String data) {
		super.getUserSignLog().setAction(UserSignLog.ACTION_SYNC_DELETE);
		
		List<Long> idList = JSON.parseArray(data, Long.class);
		
		try {
			ridingLineService.deleteByIds(idList);
			
		} catch (Exception e) {
			logger.error("delete ridingline failuer.", e);
			return resultEntity.failure();
		}
		
		return resultEntity.success(idList);
	}
	
	@RequestMapping(headers="api-version=1", value="/download/count")
	public @ResponseBody ResultEntity downloadCount(HttpServletRequest request) {
		super.getUserSignLog().setAction(UserSignLog.ACTION_SYNC_DOWNLOAD_COUNT);
		
		String lastTimestamp = request.getParameter("lastTimestamp");
		String rlIdStr = request.getParameter("rlId");
		
		Long count = linePointService.countByLastTime(super.getUserId(), rlIdStr, lastTimestamp);
		
		return resultEntity.success(count);
	}
	
	@RequestMapping(headers="api-version=1", value="/download")
	public @ResponseBody ResultEntity download(HttpServletRequest request) {
		super.getUserSignLog().setAction(UserSignLog.ACTION_SYNC_DOWNLOAD);
		
		String lastTimestamp = request.getParameter("lastTimestamp");
		String rlIdStr = request.getParameter("rlId");
		
		SyncDataEntity downloadEntity = new SyncDataEntity();
		
		Long count = linePointService.countByLastTime(super.getUserId(), rlIdStr, lastTimestamp);
		
		RidingLine rl = null;
		if ( StringUtils.isNotEmpty(rlIdStr) ) {
			rl = ridingLineService.findById(Long.parseLong(rlIdStr));
		} else {
			rl = ridingLineService.findFirst();
		}
		
		if ( rl == null ) {  //###如果查询不到骑记该如何处理
			
			
			downloadEntity.setEntity(new RidingLine());
			downloadEntity.setSubEntityList(new ArrayList<LinePoint>());
			return resultEntity.success(downloadEntity);
		} else {
			rl.setRemoteId(rl.getId());
			rl.setId(null);
			downloadEntity.setEntity(rl);
			
			QueryEntity query = new QueryEntity(1, 10);
			query.put("userId", super.getUserId());
			query.put("rlId", rl.getRemoteId());
			query.put("lastTimestamp", lastTimestamp);
			
			List<LinePoint> lpList = linePointService.findBy(query);
			if ( CollectionUtils.isEmpty(lpList) ) {
				if ( StringUtils.isNotEmpty(rlIdStr) ) {
					RidingLine rl2 = ridingLineService.findNextById(rl.getRemoteId());
					if ( rl2 != null ) {
						rl2.setRemoteId(rl2.getId());
						rl2.setId(null);
						downloadEntity.setEntity(rl2);
						
						query.put("rlId", rl2.getRemoteId());
						query.put("lastTimestamp", null);
						lpList = linePointService.findBy(query);
						if ( CollectionUtils.isNotEmpty(lpList) ) {
							downloadEntity.setSubEntityList(lpList);
						} else {
							downloadEntity.setSubEntityList(new ArrayList<LinePoint>());
						}
					} else {
						downloadEntity.setSubEntityList(new ArrayList<LinePoint>());
					}
				} else {
					downloadEntity.setSubEntityList(new ArrayList<LinePoint>());
				}
			} else {
				downloadEntity.setSubEntityList(lpList);
			}
			
			downloadEntity.setPageSize(query.getRows());
			downloadEntity.setTotalSize(count - lpList.size());
		}
		
		return resultEntity.success(downloadEntity);
	}
	
//	@RequestMapping("/upload")
	@RequestMapping(headers="api-version=1", method=RequestMethod.POST, value="/upload") //All
	public @ResponseBody ResultEntity upload(@RequestParam("data") String data) {
		super.getUserSignLog().setAction(UserSignLog.ACTION_SYNC_UPLOAD);
		
		if (StringUtils.isNotEmpty(data)) {
			System.out.println("upload data:"+data);;
			SyncDataEntity uploadEntity = JSON.parseObject(data, SyncDataEntity.class);
					
			RidingLine rl = uploadEntity.getEntity();
			
			if ( rl != null ) {
				SyncIdEntity syncIdEntity = new SyncIdEntity();
				List<SyncIdEntity> subIdEntity = new ArrayList<SyncIdEntity>();
				
				if ( rl.getRemoteId() != null && rl.getRemoteId() != 0 ) {
					RidingLine rlTemp = ridingLineService.findById(rl.getRemoteId());
					if ( rlTemp == null ) {  //###客户端已经标识为同步了，但是服务端没有这条数据，这种逻辑是有问题的
						return resultEntity.failure();
					}
					syncIdEntity.id = rl.getId();
					syncIdEntity.remoteId = rl.getRemoteId();
					rl.setId(rl.getRemoteId());
				} else {
					syncIdEntity.id = rl.getId();
					rl.setId(null);
					rl.setLastUpdateTime(DateUtils.now());
					super.setWho(rl);
					ridingLineService.save(rl);
					syncIdEntity.remoteId = rl.getId();
				}
				
				List<LinePoint> lpList = uploadEntity.getSubEntityList();
				if ( CollectionUtils.isNotEmpty(lpList) ) {
					for ( LinePoint lp : lpList ) {
						try {
							SyncIdEntity idEntity = new SyncIdEntity();
							idEntity.id = lp.getId();
							lp.setId(null);
							lp.setRidingLine(rl);
							super.setWho(lp);
							linePointService.save(lp);
							idEntity.remoteId = lp.getId();
							subIdEntity.add(idEntity);
						} catch (Exception e) {
							logger.error("save line point error!", e);
							continue ;
						}
					}
				}
				
				syncIdEntity.idList = subIdEntity;
				return resultEntity.success(syncIdEntity);
			} else {
				return resultEntity.failure();
			}
		} else {
			SyncDataEntity uploadEntity = new SyncDataEntity();
			return resultEntity.success(uploadEntity);
		}
	}
	
	public static void main(String[] args) {
//		List<Long> tidList = new ArrayList<Long>();
//		tidList.add(1l);
//		tidList.add(2l);
//		tidList.add(3l);
//		System.out.println(JSON.toJSONString(tidList));
		
//		System.out.println(DateUtils.nowTimestamp());
		
//		System.out.println((15*1000*2) / 3600);
		
		System.out.println((float) 5 / (float) 60 / (float) 60);
		
		float speed = (((float) 10 / (float)1000) / ((float) 5 / (float) 60 / (float) 60));
		System.out.println(speed);
		
//		float totalMileage = 1748.3079f;
//		float km = totalMileage / (float) 1000;
//		float hour = (float) 54 / (float) (60 * 60);
//		float s = km / hour;
//		System.out.println(hour);
	}
	
	
}
